<script setup>
import { ref } from 'vue';
import request from '@/utils/request';
import { showDefaultmsg, showSuccessMsg, showWarningMsg, showErrorMsg } from '@/utils/show-msg'
import E from "wangeditor"
import hljs from 'highlight.js'
import { nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { onMounted } from 'vue';
import { getFromLocalStorage } from '@/utils/store-data';

const BASE_URL = 'http://localhost:9999'
const userToken = getFromLocalStorage("token")
const TOKEN_PREFIX = 'Bearer '

const tableData = ref([])
const title = ref('')
const content = ref('')
const editor = ref(null)
// pagination
const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(10)
// ids
const ids = ref([])
// form
const form = ref({})
const formRef = ref(null)
const rules = ref([])
const formTitle = ref('')
const dialogVisible = ref(false)
const showContentVisible = ref(false)
const resetQuery = () => {
  title.value = ''
  getData()
}

const setRichText = () => {
  nextTick(() => {
    editor.value = new E(`#editor`)
    editor.value.highlight = hljs
    editor.value.config.uploadImgServer = BASE_URL + '/file/editor/uploadFile'
    editor.value.config.uploadFileName = 'file'
    editor.value.config.uploadImgHeaders = {
      Authorization: TOKEN_PREFIX + userToken
    }
    editor.value.config.uploadImgParams = {
      type: 'img',
    }
    editor.value.config.uploadVideoServer = BASE_URL + '/file/editor/uploadFile'
    editor.value.config.uploadVideoName = 'file'
    editor.value.config.uploadVideoHeaders = {
      Authorization: TOKEN_PREFIX + userToken
    }
    editor.value.config.uploadVideoParams = {
      type: 'video',
    }
    editor.value.create()  // 创建
  })
}

const delBatch = () => {
  if (!ids.value.length) {
    showWarningMsg("请选择要删除的数据")
    return
  } else {
    ElMessageBox.confirm('您确认批量删除这些数据吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      request({
        url: '/news/delete/batch',
        method: 'DELETE',
        data: ids.value
      }).then((res) => {
        if (res.code === '200') {
          showSuccessMsg("操作成功"),
            getData(1)
        } else {
          showErrorMsg(res.msg)
        }
      })
    }).catch(() => showDefaultmsg("取消删除"))
  }
}
const handleAdd = () => {
  formTitle.value = '新增新闻'
  dialogVisible.value = true
  setRichText()
}
const handleSelectionChange = (rows) => ids.value = rows.map(e => e.id)
const showContent = (_content) => {
  content.value = _content
  showContentVisible.value = true
}
const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
  setRichText()

  nextTick(() => { editor.value.txt.html(row.content) })
}
const del = (id) => {
  ElMessageBox.confirm(
    '确定要删除吗',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    request({
      url: `/news/delete/${id}`,
      method: 'DELETE'
    }).then((res) => {
      if (res.code === '200') {
        showSuccessMsg("操作成功")
        getData(1)
      } else {
        showErrorMsg(res.msg)
      }
    })
  }).catch(() => {
    showDefaultmsg("取消删除")
  })
}
const handleCurrentChange = (newPageNum) => getData(newPageNum)
const handleDialogCancel = () => {
  form.value = {}
  formTitle.value = ''
  dialogVisible.value = false
}
const handleDialogSubmit = () => {
  formRef.value.validate(valid => {
    if (!valid) {
      showErrorMsg("请填写完整信息 再提交")
    } else {
      content.value = editor?.value?.txt?.html()
      form.value.content = content
      console.log(content.value)
      request({
        url: form.value.id ? '/news/update' : '/news/add',
        method: form.value.id ? 'PUT' : 'POST',
        data: form.value
      }).then(res => {
        if (res.code === '200') {
          showSuccessMsg("操作成功")
          getData(1)
          form.value = {}
          dialogVisible.value = false
        } else {
          showErrorMsg(res.msg)
        }
      })
    }
  })
}
const router = useRouter()
const handleDetailShow = (id) => router.push(`/newsDetail?id=${id}`)
const closeDialog = () => {
  editor.value.destroy()
  editor.value = null
}

const getData = (newPageNum) => {
  if (newPageNum) pageNum.value = newPageNum
  // content.value = editor?.value?.txt?.html()
  // form.value.content = content
  // console.log(form.value.content)
  request({
    url: '/news/selectByPage',
    method: 'get',
    params: {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      title: title.value
    }
  }).then(res => {
    tableData.value = res.data.records
    total.value = res.data.total
  })
}

onMounted(() => getData(1))
</script>

<template>
  <div class="content">
    <!-- query -->
    <div>
      <el-input style="width: 200px" placeholder="查询标题" v-model="title"></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="getData(1)">查询</el-button>
      <el-button type="info" @click="resetQuery">重置</el-button>
    </div>
    <!-- btn -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <!-- table -->
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="description" label="简介"></el-table-column>
      <el-table-column prop="content" label="内容">
        <template v-slot="scope">
          <el-button @click="showContent(scope.row.content)">显示内容</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="详情页">
        <template v-slot="scope">
          <el-button @click="handleDetailShow(scope.row.id)">在详情页显示</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="发布人"></el-table-column>
      <el-table-column prop="time" label="发布时间"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination -->
    <div style="margin: 10px 0">
      <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize"
        layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <!-- dialog -->
    <el-dialog v-model="dialogVisible" :title="formTitle" width="70%" @close="closeDialog">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="标题" prop="title"> <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="content"> <el-input v-model="form.description" placeholder="简介"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <!-- dialog footer -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="handleDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleDialogSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- show content dialog -->
    <el-dialog title="内容" v-model="showContentVisible" width="70%">
      <el-card class="w-e-text">
        <div v-html="content"></div>
      </el-card>
      <div class="dialog-footer" slot="footer">
        <el-button type="primary" @click="showContentVisible = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.content {}
</style>
